package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.service.UserService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;
    // 获取用户名显示在右上角
    @RequestMapping("/getUsername")
    public Result getUsername(){
        // 获取保存在session中认证的上下文对象
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        // 这个可以直接获取登录的用户名
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        if (user==null){
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
        String username = user.getUsername();
        return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
    }
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return userService.findPage(queryPageBean);
    }
    @RequestMapping("/add")
    public Result add(@RequestBody Map<String,Object> map){

        try {
            userService.add(map);
            return new Result(true, MessageConstant.ADD_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_USER_FAIL);
        }
    }

    @RequestMapping("/edit")
    public Result edit(@RequestBody Map<String,Object> map){
        System.out.println(map);
        try {
            userService.edit(map);
            return new Result(true, MessageConstant.EDIT_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_USER_FAIL);
        }
    }
    @RequestMapping("/deleteById/{id}")
    public Result deleteById( @PathVariable Integer id){
        System.out.println(id);
        try {
//            Integer id  = Integer.parseInt(ids);
            userService.delete(id);
            return new Result(true,MessageConstant.DELETE_USER_SUCCESS);
        }
        catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_USER_FAIL);
        }

    }
}
